<template>
  <el-dialog
      v-model="dialogVisible"
      title="查看详情"
      :close-on-click-modal="false"
      width="80%"
      class="fixed-footer-dialog"
  >
    <div class="boxs dialog-content-scroll">
      <div>
        <div class="title-col">
          <span>项目信息</span>
          <el-link
              type="primary"
              v-if="projectInfo.processInstanceId != null && projectInfo.processInstanceId != ''"
              class="title-right"
              @click="checkHistoryModalVisible = true"
          >
            审核记录
          </el-link>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            {{ projectInfo.projectName }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ projectInfo.chargerName }}
          </el-descriptions-item>
          <el-descriptions-item label="合同金额（万元）">
            {{ turnWanyuan(projectInfo.feeAuthorize) }}
          </el-descriptions-item>
          <el-descriptions-item label="所属单位">
            {{ projectInfo.unitName }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="title-col">报销经费</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报销人">
            {{ projectInfo.payoutPersonName }}
          </el-descriptions-item>
          <el-descriptions-item label="财务项目编号">
            {{ projectInfo.feeCode }}
          </el-descriptions-item>
          <el-descriptions-item label="支出金额（元）">
            {{ projectInfo.payoutFee }}
          </el-descriptions-item>
          <el-descriptions-item label="支出时间">
            {{ projectInfo.payoutDate }}
          </el-descriptions-item>
          <el-descriptions-item label="支出科目">
            {{ projectInfo.payoutSubjectName }}
          </el-descriptions-item>
          <el-descriptions-item label="摘要">
            {{ projectInfo.note }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="flex-title-btn">
          <div class="title-col">报销经费明细</div>
        </div>

        <el-table :data="reimbursementDetails" border>
          <el-table-column label="经费来源">
            <template #default="scope">
              {{ scope.row.feesource === '1' ? '专项' : (scope.row.feesource === '2' ? '配套' : '') }}
            </template>
          </el-table-column>
          <el-table-column label="报销科目名称">
            <template #default="scope">
              {{ scope.row.payoutSubjectName }}
            </template>
          </el-table-column>
          <el-table-column label="预算科目名称 (余额) 单位：元">
            <template #default="scope">
              {{ getBudgetSubjectLabel(scope.row.budgetSubjectId) }}
            </template>
          </el-table-column>
          <el-table-column label="每项报销金额（元）">
            <template #default="scope">
              {{ scope.row.payoutFee }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div v-if="showCheckcomponents">
        <Checkcomponents :procInsId="procInsId"  @success="success" class="mt-[10px]" />
      </div>
      <div class="dialog-footer">

<!--        <el-button @click="handleSave">保存</el-button>-->
<!--        <el-button type="primary" @click="handleSaveAndPass">保存并通过</el-button>-->
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <CheckHistoryModal
      v-model="checkHistoryModalVisible"
      :procInsId="projectInfo.processInstanceId"
      :checker="projectInfo.checker"
      :checkDate="projectInfo.checkdate"
  />
</template>

<script setup>
import { ref, defineEmits, watch } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { getCategory, selectVproject, getpayoutInfo, add, getEditInfo, edit } from "./../../../api/money/jfzcApi.js";
import Cookies from "js-cookie";
import { turnWanyuan } from '@/utils/money.js';
//查看审核流程
const  checkHistoryModalVisible = ref(false)
// checkdate: "2025-05-06 13:41:24"
// checker: "白雪



//审核
const emit = defineEmits(['Getlist'])
const showCheckcomponents = ref(false)
import Checkcomponents from "@/views/flowable/processInstance/detail/components.vue";
import CheckHistoryModal from "@/views/project/components/CheckHistoryModal.vue";
const procInsId = ref('')
const success = function (){
  emit('Getlist')
  dialogVisible.value = false
}
//审核
// 项目名称下拉框选项
const projectOptions = ref([]);
// 处理输入值的函数
const handleInput = (inputValue) => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    name: inputValue.data
  })
      .then((res) => {
        projectOptions.value = res.rows
      })
};
// 获取项目下拉
const getprojectOptions = () => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
  })
      .then((res) => {
        projectOptions.value = res.rows
      })
}
// 点击项目名称下拉
const DialogTop = ref({})
const changeprojectOptions = (itemObj) => {
  DialogTop.value = projectOptions.value.find((item) => item.projectId === projectInfo.value.projectId);
  Object.assign(projectInfo.value, DialogTop.value)
  projectInfo.value.id = null
}
const payoutFeeId= ref(''); // 用于存储当前行的主表ID,查看时，根据状态来，审核通过和审核中的数据，余额就包含当前数据的金额
//暂存和不通过，就要排除掉当前行的金额。
// 获取预算科目
const getbudgetSubjects = (index, row) => {
  getpayoutInfo({
    projectId: projectInfo.value.projectId,
    feesource: reimbursementDetails.value[index].feesource,
    projectClass: projectInfo.value.projectClass,
    id: payoutFeeId.value
  }).then((res) => {
    budgetSubjects.value = res.data;
    // 确保选中的预算科目名称更新
    const selectedSubject = budgetSubjects.value.find(item => item.code === row.budgetSubjectId);
    if (selectedSubject) {
      reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
    }
  })
}
// 处理预算科目名称选择变化
const handleSelectChange = (index, row) => {
  const rowCode = row.budgetSubjectId;
  const selectedSubject = budgetSubjects.value.find(item => item.code === rowCode);
  reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
};

// 报销科目名称树形选项
const baoxiaokemuOptions = ref([])
const getbaoxiaokemuOptions = () => {
  getCategory({
    'bizName': '经费支出科目'
  })
      .then((res) => {
        baoxiaokemuOptions.value = res.data
      })
}
const reimbursementSubjectOptions = ref([
  {
    value: '一级科目 1',
    label: '一级科目 1',
    children: [
      {
        value: '二级科目 1-1',
        label: '二级科目 1-1'
      },
      {
        value: '二级科目 1-2',
        label: '二级科目 1-2'
      }
    ]
  },
  {
    value: '一级科目 2',
    label: '一级科目 2'
  }
]);

// 预算科目名称选项
const budgetSubjects = ref([]);

// 格式化预算科目数据，将 label 和 availableFee 组合
const formatBudgetSubjects = (data) => {
  return data.map(item => {
    const newItem = {...item};
    if (newItem.availableFee !== undefined) {
      newItem.value = `${newItem.value} (余额: ${newItem.availableFee})`;
    }
    if (newItem.children && newItem.children.length > 0) {
      newItem.children = formatBudgetSubjects(newItem.children);
    }
    return newItem;
  });
};

function findNodeInTree(tree, targetCode) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.code === targetCode) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findNodeInTree(node.children, targetCode);
      if (found) {
        return found;
      }
    }
  }
  return null;
}

// 根据 budgetSubjectId 获取完整的预算科目名称
const getBudgetSubjectLabel = (budgetSubjectId) => {
  //console.log(budgetSubjectId)
 // console.log(budgetSubjects.value)
  const subject =  findNodeInTree(budgetSubjects.value ,budgetSubjectId )
  //const subject = budgetSubjects.value.find(item => item.code === budgetSubjectId);
 // console.log(subject)
  return subject ? formatBudgetSubjects([subject])[0].value : '';
};

// 报销经费明细数据
const reimbursementDetails = ref([]);

// 判断是否可以添加行
const canAddRow = () => {
  return reimbursementDetails.value.every(row => {
    return (
        row.feesource &&
        row.payoutSubjectId &&
        row.budgetSubjectId &&
        row.payoutFee > 0
    );
  });
};

// 添加一行数据
const addRow = () => {
  if (canAddRow()) {
    reimbursementDetails.value.push({
      feesource: '1',
      payoutSubjectId: '',
      payoutSubjectName: '',
      budgetSubjectId: '',
      budgetSubjectName: '',
      payoutFee: 0
    });
  } else {
    ElMessage({
      // title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
  }
};

// 计算总支出金额
const calculateTotalExpense = () => {
  const total = reimbursementDetails.value.reduce((sum, row) => {
    return sum +  Number(row.payoutFee);
  }, 0);
  projectInfo.value.payoutFee = total;
};
watch(
    () => reimbursementDetails.value.map(row => row.payoutFee),
    () => {
      calculateTotalExpense();
    },
    {deep: true}
);

// 删除一行数据
const deleteRow = (index, row) => {
  reimbursementDetails.value.splice(index, 1);
};

// 处理报销科目名称选择变化
const handleSubjectChange = (index, data) => {
  reimbursementDetails.value[index].payoutSubjectName = data.label;
};

// 处理预算科目名称树形选择变化
const handleBudgetSubjectChange = (index, data, node) => {
  if (!data.children) {
    const rowCode = data.code;
    const selectedSubject = budgetSubjects.value.find(item => item.code === rowCode);
    reimbursementDetails.value[index].budgetSubjectName = selectedSubject.value;
    reimbursementDetails.value[index].budgetSubjectId = rowCode;
  } else {
    reimbursementDetails.value[index].budgetSubjectName = null;
    reimbursementDetails.value[index].budgetSubjectId = null;
  }
};

// 控制弹窗显示与隐藏的变量
const dialogVisible = ref(false);
// 获取当前日期
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
// 模拟项目信息数据
const projectInfo = ref({
  status: '-1',
  checkstatus: '',
  projectId: "",
  projectName: "",
  chargerName: "",
  feeAuthorize: '',
  unitId: '',
  unitName: '',
  projectClass: '',
  payoutPersonName: '',
  payoutPersonId: "",
  feeCode: "",
  payoutFee: 0,
  payoutDate: formattedDate,
  payoutSubjectName: "",
  note: "",
  payoutDetails: []
});

// 报销经费信息
const reimbursementInfo = ref({
  reimburser: '李四',
  financialProjectNumber: '',
  expenseAmount: 0,
  expenseDate: formattedDate,
  expenseSubject: '',
  summary: ''
});

// 保存按钮点击事件处理函数
const handleSave = () => {
  projectInfo.value.status = '-1';
  projectInfo.value.payoutDetails = reimbursementDetails.value;
  if (!canAddRow()) {
    ElMessage({
      // title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
    return;
  }
  edit(projectInfo.value)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          });
          dialogVisible.value = false;
          emits('getslist');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      });
};

// 保存并通过按钮点击事件处理函数
const handleSaveAndPass = () => {
  projectInfo.value.status = '2';
  projectInfo.value.payoutDetails = reimbursementDetails.value;
  if (!canAddRow()) {
    ElMessage({
      // title: '提示',
      message: '请先将表格中的行数据填写完整，再添加新行。',
      type: 'warning'
    });
    return;
  }
  edit(projectInfo.value)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          });
          dialogVisible.value = false;
          emits('getslist');
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          });
        }
      });
};

// 定义一个方法用于打开弹窗
const openDialog = (row, name) => {
  dialogVisible.value = true;
  if(row.checkstatus !='2'){
  // 如果是审核通过，不存当前行的主表ID
    payoutFeeId.value = row.id; 
  }
  getEditInfo({
    id: row.id
  })
      .then((res) => {
        projectInfo.value = res.data;
        reimbursementDetails.value = res.data.payoutDetails;
        getbaoxiaokemuOptions();
        reimbursementDetails.value.forEach((currentRow, index) => {
          getbudgetSubjects(index, currentRow);
        });
      });
  // alert(name)
   //console.log(row)
  if(row.hasOwnProperty('isAuditor') && row.isAuditor === true){
    if (row.checkstatus == 1 && name != 'name') {
      if (row.processInstanceId == null) {
        ElMessage({
          message: 'processInstanceId为空',
          type: "error"
        });
        return
      }
      showCheckcomponents.value = true
      console.log(row)
      procInsId.value = row.processInstanceId

    }else if(row.checkstatus == null && name == 'shenhename'){
      if (row.processInstanceId == null) {
        ElMessage({
          message: 'processInstanceId为空',
          type: "error"
        });
        return
      }
      showCheckcomponents.value = true
      console.log(row)
      procInsId.value = row.processInstanceId
    }
  }else if( name == 'shenhename'){
    showCheckcomponents.value = true
    if (row.processInstanceId == null) {
      ElMessage({
        message: 'processInstanceId为空',
        type: "error"
      });
      return
    }
    console.log(row)
    procInsId.value = row.processInstanceId
  } else {
    showCheckcomponents.value = false
    if (row.processInstanceId == null) {
      ElMessage({
        message: 'processInstanceId为空',
        type: "error"
      });
      return
    }
    console.log(row)
    procInsId.value = row.processInstanceId
  }


};
// 定义事件，用于通知父组件保存操作
//const emits = defineEmits(['getslist',]);
// 暴露 openDialog 方法供父组件调用
defineExpose({
  openDialog
});
</script>

<style scoped  lang="scss">
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 设置标题宽度 */
:deep(.el-descriptions__label) {
  width: 200px;
}

/* 让内容居中显示 */
:deep(.el-descriptions__content) {
  text-align: center;
}

.title-col {
  color: #337AB7;
  font-weight: bolder;
  margin: 10px 0;
}

.flex-title-btn {
  display: flex;
  justify-content: space-between;
}

.boxs > div {
  margin: 10px 0;
}
.title-right{
  margin-left: 89%;
}

/* 固定高度和滚动条样式 */
.bottom{
  position: absolute;
  top: 550px;
  width: 98%;
  z-index: 99;
  background-color: #da1a1a;
}
.fixed-footer-dialog {
  .el-dialog__body {
    max-height: 40vh; // 设置最大高度为视口高度的60%
    overflow-y: auto; // 添加垂直滚动条
    padding-bottom: 80px; // 为固定底部留出空间
  }

  .el-dialog__footer {
    position: absolute; // 使用绝对定位而非固定定位
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
    z-index: 10; // 确保在内容之上
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  }
}

/* 优化表格区域的滚动体验 */
.dialog-content-scroll {
  max-height: 50vh; // 限制表格最大高度
  overflow: auto;
  display: block; // 确保表格正确处理高度

}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>